<template>
  <div class="upload-file-box">
    <div class="file-content">
      <div
        class="file-browse"
        @click.stop="handlerOpen">
        <p style="line-height: 19px">{{ uploadText }}</p>
        <input
          ref="inputFile"
          type="file"
          @change="changeFile" />
      </div>
      <input
        v-model="fileName"
        class="fileName"
        readonly
        :placeholder="placeholder" />
    </div>
    <div
      class="btn-upload"
      v-if="showUploadConfirm">
      <el-button type="primary">
        {{ uploadConfirmText }}
      </el-button>
    </div>
  </div>
</template>
<script lang="ts">
import { ElMessage } from 'element-plus';

export default {
  name: 'UploadFile',
  props: {
    fileType: {
      type: String,
      default: 'xlsx',
    },
    placeholder: {
      type: String,
      default: '',
    },
    beforeUpload: {},
    uploadText: {
      type: String,
      default: '浏览',
    },
    showUploadConfirm: {
      type: Boolean,
      default: false,
    },
    uploadConfirmText: {
      type: String,
      default: '上传',
    },
  },
  data() {
    return {
      fileName: '',
      beforeRender: false,
    };
  },
  methods: {
    handlerOpen() {
      if (this.beforeUpload && typeof this.beforeUpload === 'function') {
        if (!this.beforeUpload()) {
          this.$refs.inputFile.click();
        }
        return false;
      }
      this.$refs.inputFile.click();
    },
    changeFile(e) {
      //if(this.fileType)
      const fileName = e.target.files[0].name;
      const fileType = fileName.substr(fileName.lastIndexOf('.') + 1);
      if (this.fileType.indexOf(fileType) < 0) {
        e.target.value = '';
        ElMessage.warning(`仅支持上传${this.fileType}的格式文件`);
        return false;
      }
      this.fileName = fileName;
      this.$emit('changeFile', e.target.files[0]);
    },
  },
};
</script>
<style lang="scss" scoped>
.upload-file-box {
  flex: 1;
  display: flex;
  align-items: center;
  .btn-upload {
    flex: none;
    margin-left: 8px;
  }
}
.file-content {
  display: flex;
  align-items: center;
  width: 100%;
  box-sizing: border-box;
  box-shadow: 0 0 0 1px rgb(220, 223, 230);
  border-radius: 4px;
  .file-browse {
    flex: none;
    position: relative;
    padding: 6.5px 15px;
    border-right: 1px solid rgb(220, 223, 230);
  }
  .fileName {
    flex: 1;
    padding: 0 8px;
    border: 0;
    outline: none;
  }
}
.file-browse {
  input[type='file'] {
    cursor: pointer;
    z-index: -1;
    display: block;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
  }
}
</style>
